package com.ttg.web.utils;

import com.ttg.common.enums.MerchDimTypeEnum;
import com.ttg.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/10/9 13:57
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Slf4j
public class CostGradingUtil {
    //保存商户维度成本分档 各类计算金额
    private static InheritableThreadLocal<Map<MerchDimTypeEnum,Map<String, HashMap<String, BigDecimal>>>> dimMap = new InheritableThreadLocal<>();

    private CostGradingUtil(){}


    public static void putResult(MerchDimTypeEnum dimType,String months, String subKey, BigDecimal subVal){
        Map<MerchDimTypeEnum,Map<String, HashMap<String, BigDecimal>>> dimMap = getDimMap();
        boolean isNullFlag = false;
        if(dimMap==null || dimMap.isEmpty()){
            dimMap = new HashMap<MerchDimTypeEnum,Map<String, HashMap<String, BigDecimal>>>();
            isNullFlag = true;
        }

        Map<String, HashMap<String, BigDecimal>> monthMap = dimMap.get(dimType);
        if(monthMap==null){
            monthMap = new HashMap<String, HashMap<String, BigDecimal>>();
            dimMap.put(dimType,monthMap);
        }

        HashMap<String, BigDecimal> subMap = monthMap.get(months);
        if(subMap==null){
            subMap = new HashMap<String,BigDecimal>();
            monthMap.put(months,subMap);
        }
        subMap.put(subKey,subVal);


        if(isNullFlag){
            setDimMap(dimMap);
        }
    }

    public static BigDecimal getResult(MerchDimTypeEnum dimType,String months, String subKey){
        Map<MerchDimTypeEnum,Map<String, HashMap<String, BigDecimal>>> dimMap = getDimMap();
        if(dimMap==null || dimMap.isEmpty()){
            return new BigDecimal(0);
        }

        Map<String, HashMap<String, BigDecimal>> monthMap = dimMap.get(dimType);
        if(monthMap==null){
            return new BigDecimal(0);
        }
        HashMap<String, BigDecimal> subMap = monthMap.get(months);
        if(subMap==null){
            return new BigDecimal(0);
        }
        BigDecimal val = subMap.get(subKey);
        if(val==null){
            log.error("没有该值 key:{}",subKey);
//            throw new BaseException("没有该值 key:" + subKey);
        }
        return subMap.get(subKey);
    }


    public static Map<MerchDimTypeEnum,Map<String, HashMap<String, BigDecimal>>> getDimMap(){
        return dimMap.get();
    }

    public static void setDimMap(Map<MerchDimTypeEnum,Map<String, HashMap<String, BigDecimal>>> paramap){
        dimMap.set(paramap);
    }

    public static void removeDimMap(){
        dimMap.remove();
    }

}
